package com.nd.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.digest.MD5;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nd.OSS.OSSBootUtil;
import com.nd.dao.StorageMapper;
import com.nd.pojo.bean.Role;
import com.nd.pojo.bean.Storage;
import com.nd.pojo.bean.StorageExample;
import com.nd.pojo.bo.StorageListBO;
import com.nd.pojo.vo.ErrorAndErrno;
import com.nd.pojo.vo.ListItems;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class  StorageServiceImpl implements StorageService {

//
//    private String filePath = "/Users/wanghongliang/Downloads/wannaGetAll/后端/30th/projects/project2/project2git/project2mall/src/main/resources/static/image";
//    private String urlPath = "http://localhost:8083/static/image/";

    @Autowired
    StorageMapper storageMapper;

    @Autowired
    OSSBootUtil bootUtil;

//    @Autowired
    String token="";

    @Override
    @Transactional
    public Storage uploadFiles(MultipartFile myFile) throws Exception {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(requestAttributes).getRequest();

        String headerToken = request.getHeader("X-cskaoyan-mall-Admin-Token");
        if (headerToken!=null){
            token=headerToken;
        }
        String url = "";
        String fileType  = myFile.getContentType();

        String updateTime = DateTime.now().toDateStr();
        String uuid = UUID.randomUUID().toString();


        byte[] bytes = myFile.getBytes();
        String collision = MD5.create().digestHex(bytes);

        List<Storage> storages = storageMapper.selectByKey(collision);
        if (storages.isEmpty()){
            String filename = fileType+"/"+updateTime+"/"+uuid+"-"+myFile.getOriginalFilename();
            url = "http://"+bootUtil.getSufferUrl()+"/"+filename;
            OSSClient ossClient = bootUtil.getOSSClient(token);
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(myFile.getBytes());
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentDisposition("inline");
            objectMetadata.setContentType(fileType);
            try {
                ossClient.putObject(bootUtil.getBUCKETNAME(),filename,byteArrayInputStream);
            } catch (OSSException | ClientException e) {
                e.printStackTrace();
            } finally {
                bootUtil.closeOSSClient();
            }
        }else {
            url=storages.get(0).getUrl();
        }

        System.out.println(url);

        String originalFilename =uuid+ myFile.getOriginalFilename();
        String name = myFile.getName();//请求参数名
        //获得上传文件的类型
        String contentType = myFile.getContentType();
        //文件的大小
        long size = myFile.getSize();
        //将文件上传至指定路径

        Date now = new Date();
        Storage storage = new Storage(null, collision, originalFilename, contentType, size, url, now, now, false);
        int i = storageMapper.insertSelective(storage);
        if (i == 0) return null;
        StorageExample storageExample = new StorageExample();
        storageExample.createCriteria().andNameEqualTo(originalFilename);
        List<Storage> storages1 = storageMapper.selectByExample(storageExample);
        return storages1.get(0);
    }

    @Override
    public ErrorAndErrno<ListItems<Storage>> slectStorageList(StorageListBO bo) {
        ErrorAndErrno<ListItems<Storage>> errorAndErrno = new ErrorAndErrno<>();

        PageHelper.startPage(bo.getPage(),bo.getLimit());

        StorageExample example = new StorageExample();
        example.setOrderByClause(bo.getSort() + " " + bo.getOrder());

        List<Storage> storages = storageMapper.selectByKeyAndName(bo.getKey(), bo.getName());
        PageInfo<Storage> storagePageInfo = new PageInfo<>(storages);
        long total = storagePageInfo.getTotal();
        ListItems<Storage> items = new ListItems<>(storages);
        items.setTotal(total);
        errorAndErrno.setData(items);

        return errorAndErrno;
    }

    @Override
    @Transactional
    public ErrorAndErrno updateStorage(int id,String name) throws Exception {
        StorageExample storageExample = new StorageExample();
        StorageExample.Criteria criteria = storageExample.createCriteria();
        Storage storage = new Storage();
        storage.setId(id);
        int i;
        if (name==null){
        storage.setDeleted(true);
            i = storageMapper.updateByPrimaryKeySelective(storage);
        }else {
            storage.setName(name);
            i = storageMapper.updateByPrimaryKeySelective(storage);
        }
        if (i!=1)throw new Exception("该动作失败,请重试");

        return new ErrorAndErrno();
    }
}
